<template xmlns="">
    <div>
        {{studSearchFrom}}
        <!--        条件查询-->
        <el-form :inline="true" :model="studSearchFrom" class="demo-form-inline" style="text-align: left">

            <el-form-item>
                <el-input v-model="studSearchFrom.sname" placeholder="学生姓名"></el-input>
            </el-form-item>

            <el-form-item>
                <el-input v-model="studSearchFrom.addr" placeholder="学生住址"></el-input>
            </el-form-item>

            <el-from-item>
                <el-select v-model="studSearchFrom.cid" placeholder="所在班级">
                    <el-option label="所有班级" value="0"/>
                    <el-option v-for="c in classes" :label="c.cname" :value="c.cid"/>
                </el-select>
            </el-from-item>

            <el-form-item>
                <el-button type="primary" @click="search" size="middle"  style="margin-left: 20px">查询</el-button>
                <el-button type="primary" @click="add" size="middle" plain style="margin-left: 20px">添加</el-button>
                <el-button type="primary" @click="handleDelete" size="middle" plain style="margin-left: 20px">批量删除</el-button>
            </el-form-item>

        </el-form>

        <!--        学生列表展示-->
        <el-table
            :data="students"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
                    type="selection">
            </el-table-column>
            <!--prop:对应字段的名字-->
            <el-table-column
                    label="学号"
                    prop="sid"
                    align="center"
                    width="110">
            </el-table-column>

            <el-table-column
                    label="姓名"
                    prop="sname"
                    align="center"
                    width="180">
            </el-table-column>

            <el-table-column
                    label="班级"
                    prop="cname"
                    align="center"
                    width="150">
            </el-table-column>

            <el-table-column
                    label="年龄"
                    prop="age"
                    align="center"
                    width="150">
            </el-table-column>

            <el-table-column
                    label="性别"
                    prop="sex"
                    align="center"
                    width="150">
            </el-table-column>

            <el-table-column
                    label="住址"
                    prop="addr"
                    align="center"
                    width="180">
            </el-table-column>

            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
<!--        分页功能,@表示事件(方法)  :表示变量-->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next"
                :total="total">
        </el-pagination>
<!--编辑学生的对话框-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            {{stud}}
            <el-form :model="stud" :rules="rules" ref="ruleForm">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
                    <el-input v-model="stud.sname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生性别" :label-width="formLabelWidth" align="left" prop="sex">
                    <el-radio v-model="stud.sex" label="男" value="男"/>
                    <el-radio v-model="stud.sex" label="女" value="女"/>
                </el-form-item>
                <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model.number="stud.age" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="stud.addr" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="所在班级" :label-width="formLabelWidth"  prop="cid">
                    <el-select v-model="stud.cid">
                        <el-option v-for="c in classes" :label="c.cname" :value="c.cid"/>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
    import list from "@/views/classes/list";

    export default {
        data() {
            //自定义验证规则
            let checkAge=(rule,value,callback)=>{
                if (!value){
                     callback(new Error('年龄不能为空'));
                }else if (value>100||value<=0){
                     callback(new Error('年龄范围在1-100之间'));
                }else {
                     callback()
                }
            }
            return {
                // 学生数组
                students:[],
                //当前第几页的默认值
                page:1,
                //每页的大小
                pageSize:5,
                //数据总数
                total:100,
                studSearchFrom:{},
                classes:[],//所有班级
                dialogFormVisible:false,  //编辑学生对话框打开/关闭
                formLabelWidth:'100px',
                stud:{},  //表单中关联的学生对象
                title:'',  //修改表单标题
                multipleSelection:[],  //勾选的对象数组
                sids:[],//学生编号的数组
                rules:{
                    //验证用户名
                    sname:[
                        //非空验证,关注焦点离开时验证
                        { required: true, message: '请输入学生姓名', trigger: 'blur' },
                    ],
                    sex:[
                        { required: true, message: '请选择学生性别', trigger: 'change' },
                    ],
                    //自定义验证规则
                    age:[
                        {validator:checkAge,required: true,trigger:'blur'}
                    ],
                    addr:[
                        { required: true, message: '请输入学生住址', trigger: 'blur' },
                    ],
                    cid:[
                        { required: true, message: '请选择班级编号', trigger: 'change' },
                    ]
                }
            }
        },
        created() {
            //查询所有学生
            // this.findStudents();
            //分页查询
            // this.findByPage();
            this.findClasses();
            //条件查询带分页
            this.search();
        },
        methods: {
            findStudents() {
                this.$axios.get("/student?cmd=list").then(({data})=> {
                    if (data.code === 0) {
                        this.students=data.list
                    }
                })
            },
            add(){
                this.title='添加学生'
                //打开对话框
                this.dialogFormVisible=true;
                //清空表单数据
                this.stud={}
            },
            //修改学生
            handleEdit(index, row) {
                //打开对话框
                this.dialogFormVisible=true;
                this.title='修改学生';
                //绑定表单数据
                this.stud=row
            },
            //删除学生
            handleDelete(index, row) {
                let _this=this
                //处理要删除的学生ID数组,得到要删除的sid
                if (row){
                    this.sids=[row.sid]
                }else {
                    this.sids=this.multipleSelection.map(m=>m.sid)
                }
                //确认删除
                    this.$confirm(`此操作将永久删除学号为${this.sids}的学生, 是否继续?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        //点击确定后,向后台发送数据
                        this.$axios.get(`/student?cmd=delete&sids=${this.sids}`)
                            .then(({data})=> {
                                //如果添加修改成功,则执行一次查询方法刷新页面
                                if (data.code === 0) {
                                    this.$message({
                                        type: 'success',
                                        message: data.message,
                                        onClose(){
                                            _this.search()
                                        }
                                    });
                                }
                            })
                    })
            },
            // 分页查询((page-1)*pageSize(从第几条开始),pageSize(查询几条))
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize=val
                this.search()
            },
            //更改页数时触发的事件
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.page=val
                this.search()
            },
            findByPage(){
                //发送请求
                this.$axios.get(`/student?cmd=findByPage&page=${this.page}&pageSize=${this.pageSize}`)
                    .then(({data})=> {
                    if (data.code === 0) {
                        // pr分页对象(PageResult对象)
                        //rows分页集合
                        this.students=data.pr.rows
                        //总记录数
                        this.total=data.pr.total
                    }
                })
            },
            findClasses(){
                //发送请求
                this.$axios.get(`/classes`)
                    .then(({data})=> {
                    if (data.code === 0) {
                        this.classes=data.classes
                    }
                })
            },
            search(){
                let studStr=JSON.stringify(this.studSearchFrom)
                this.$axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,"stud="+studStr)
                    .then(({data})=> {
                        if (data.code === 0) {
                            //rows分页集合
                            this.students=data.pr.rows
                            //总记录数
                            this.total=data.pr.total                        }
                    })
            },
            //确定保存数据
            //通过sid的值判断是添加还是修改
            save(){
                let url="/student?cmd=add"
                let _this=this
                if (this.stud.sid){  //有值则为修改
                    url="/student?cmd=update"
                }
                this.$refs['ruleForm'].validate((valid) => {
                    if (valid) {
                        //表单中每一项都验证通过才提交数据到后台
                        this.$axios.post(url,"stud="+JSON.stringify(this.stud))
                            .then(({data})=> {
                                //如果添加修改成功,则执行一次查询方法刷新页面
                                if (data.code === 0) {
                                    this.$message({
                                        message: data.message,
                                        type: 'success',
                                        onClose() {
                                            _this.search()
                                        }
                                    })
                                }
                                _this.dialogFormVisible = false
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });

            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
                console.log("选择行:"+val)
            }
        }
    }
</script>
<style scoped>
    .el-pagination{
        text-align: right;
        margin-top: 10px;
    }

</style>
